<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="产品类型编号" prop="productTypeCode">
        <el-input v-model="formData.productTypeCode" placeholder="请输入产品类型编号" />
      </el-form-item>
      <el-form-item label="产品类型名称" prop="productTypeName">
        <el-input v-model="formData.productTypeName" placeholder="请输入产品类型名称" />
      </el-form-item>
      <el-form-item label="产品类型" prop="productType">
        <el-select v-model="formData.productType" placeholder="请选择产品类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CARDBOARD_PRODUCTION_PRODUCT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="客户 ID" prop="customerId">-->
<!--        <el-input v-model="formData.customerId" placeholder="请输入客户 ID" />-->
<!--      </el-form-item>-->

      <el-form-item label="客户名称" prop="customerId">
        <el-select v-model="formData.customerId" placeholder="请选择客户" clearable @change="handleCustomerChange">
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
<!--      <el-form-item label="单价(英寸)" prop="unitPriceInch">-->
<!--        <el-input ref="unitPriceInchRef"  v-model="formData.unitPriceInch"-->
<!--                  placeholder="请输入单价(英寸)"  @focus="openCalculator('unitPriceInch', unitPriceInchRef)"/>-->
<!--      </el-form-item>-->

      <el-form-item label="单价(英寸)" prop="unitPriceInch">
        <el-input
          ref="unitPriceInchRef"
          v-model="formData.unitPriceInch"
          readonly
          @dblclick="openCalculator('unitPriceInch', unitPriceInchRef)"
          style="cursor: pointer;"
        />
      </el-form-item>
      <el-form-item label="面积（英寸）" prop="areaInch">
        <el-input
          ref="areaInchRef"
          v-model="formData.areaInch"
          readonly
          @dblclick="openCalculator('areaInch', areaInchRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="立方（英寸）" prop="volumeInch">
        <el-input
          ref="volumeInchRef"
          v-model="formData.volumeInch"
          readonly
          @dblclick="openCalculator('volumeInch', volumeInchRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="重量（英寸）" prop="weightInch">
        <el-input
          ref="weightInchRef"
          v-model="formData.weightInch"
          readonly
          @dblclick="openCalculator('weightInch', weightInchRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="单价（厘米）" prop="unitPriceCm">
        <el-input
          ref="unitPriceCmRef"
          v-model="formData.unitPriceCm"
          readonly
          @dblclick="openCalculator('unitPriceCm', unitPriceCmRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="面积（厘米）" prop="areaCm">
        <el-input
          ref="areaCmRef"
          v-model="formData.areaCm"
          readonly
          @dblclick="openCalculator('areaCm', areaCmRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="体积（厘米）" prop="volumeCm">
        <el-input
          ref="volumeCmRef"
          v-model="formData.volumeCm"
          readonly
          @dblclick="openCalculator('volumeCm', volumeCmRef)"
          style="cursor: pointer;"
        />
      </el-form-item>

      <el-form-item label="重量（厘米）" prop="weightCm">
        <el-input
          ref="weightCmRef"
          v-model="formData.weightCm"
          readonly
          @dblclick="openCalculator('weightCm', weightCmRef)"
          style="cursor: pointer;"
        />
      </el-form-item>
      <el-form-item label="包装数" prop="packageQuantity">
        <el-input v-model="formData.packageQuantity" placeholder="请输入包装数" />
      </el-form-item>
      <el-form-item label="规格拼接方式" prop="specConcatMode">
        <el-input v-model="formData.specConcatMode" placeholder="请输入规格拼接方式" />
      </el-form-item>
      <el-form-item label="规格分隔字符" prop="specSeparator">
        <el-input v-model="formData.specSeparator" placeholder="请输入规格分隔字符" />
      </el-form-item>
      <el-form-item label="规格单位字符" prop="specUnit">
        <el-input v-model="formData.specUnit" placeholder="请输入规格单位字符" />
      </el-form-item>
      <el-form-item label="用料默认单位" prop="defaultMaterialUnit">
        <el-input v-model="formData.defaultMaterialUnit" placeholder="请输入用料默认单位" />
      </el-form-item>
      <el-form-item label="最大纸长" prop="maxPaperLength">
        <el-input v-model="formData.maxPaperLength" placeholder="请输入最大纸长" />
      </el-form-item>
      <el-form-item label="用料报价单位" prop="materialPriceUnit">
        <el-input v-model="formData.materialPriceUnit" placeholder="请输入用料报价单位" />
      </el-form-item>
<!--      <el-form-item label="送货金额" prop="deliveryPrice">-->
<!--        <el-input v-model="formData.deliveryPrice" placeholder="请输入送货金额" />-->
<!--      </el-form-item>-->
      <el-form-item label="送货金额" prop="deliveryPrice">
        <el-input
          ref="deliveryPriceRef"
          v-model="formData.deliveryPrice"
          readonly
          @dblclick="openCalculator1('deliveryPrice', deliveryPriceRef)"
          style="cursor: pointer;"
        />
      </el-form-item>
<!--      <el-form-item label="送货总重量" prop="deliveryTotalWeight">-->
<!--        <el-input v-model="formData.deliveryTotalWeight" placeholder="请输入送货总重量" />-->
<!--      </el-form-item>-->
      <el-form-item label="送货总重量" prop="deliveryTotalWeight">
        <el-input
          ref="deliveryTotalWeightRef"
          v-model="formData.deliveryTotalWeight"
          readonly
          @dblclick="openCalculator1('deliveryTotalWeight', deliveryTotalWeightRef)"
          style="cursor: pointer;"
        />
      </el-form-item>
      <el-form-item label="总重量取舍" prop="totalWeightRounding">
        <el-select v-model="formData.totalWeightRounding" placeholder="请选择总重量取舍">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.ERP_DECIMAL_ROUNDING_MODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="取舎位数" prop="roundingDigits">
        <el-select v-model="formData.roundingDigits" placeholder="请选择取舎位数">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DECIMAL_ROUND_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefault">
        <el-radio-group v-model="formData.isDefault">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="默认加损耗" prop="defaultWithLoss">
        <el-radio-group v-model="formData.defaultWithLoss">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="BOM是否重新计价" prop="bomRecalculate">
        <el-radio-group v-model="formData.bomRecalculate">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="不进行加价设置" prop="noExtraCharge">
        <el-radio-group v-model="formData.noExtraCharge">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="按用料计算成本单价" prop="costPriceByMaterial">
        <el-radio-group v-model="formData.costPriceByMaterial">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="工艺数量按成品推算" prop="processQtyByProduct">
        <el-radio-group v-model="formData.processQtyByProduct">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="默认不上传文件" prop="noUploadFileByDefault">
        <el-radio-group v-model="formData.noUploadFileByDefault">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 计算器弹窗 -->
  <CalculatorDialog ref="calculatorRef" />
  <CalculatorDialog1 ref="calculatorRef1" />
</template>
<script setup lang="ts">
import { getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { BaseBoxTypeApi, BaseBoxTypeVO } from '@/api/erp/baseboxtype'
import {BaseBoxInnerOuterConfigApi} from "@/api/erp/baseboxinnerouterconfig";
import CalculatorDialog from "@/components/CalculatorDialog/CalculatorDialog.vue";
import CalculatorDialog1 from "@/components/CalculatorDialog/CalculatorDialog1.vue";

/** ERP基础资料-箱型资料 表单 */
defineOptions({ name: 'BaseBoxTypeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  productTypeCode: undefined,
  productTypeName: undefined,
  productType: undefined,
  customerId: undefined,
  unitPriceInch: undefined,
  areaInch: undefined,
  volumeInch: undefined,
  weightInch: undefined,
  unitPriceCm: undefined,
  areaCm: undefined,
  volumeCm: undefined,
  weightCm: undefined,
  packageQuantity: undefined,
  specConcatMode: undefined,
  specSeparator: undefined,
  specUnit: undefined,
  defaultMaterialUnit: undefined,
  maxPaperLength: undefined,
  materialPriceUnit: undefined,
  deliveryPrice: undefined,
  deliveryTotalWeight: undefined,
  totalWeightRounding: undefined,
  roundingDigits: undefined,
  isDefault: undefined,
  defaultWithLoss: undefined,
  bomRecalculate: undefined,
  noExtraCharge: undefined,
  costPriceByMaterial: undefined,
  processQtyByProduct: undefined,
  noUploadFileByDefault: undefined
})
const formRules = reactive({
  isDefault: [{ required: true, message: '是否默认不能为空', trigger: 'blur' }],
  defaultWithLoss: [{ required: true, message: '默认加损耗不能为空', trigger: 'blur' }],
  bomRecalculate: [{ required: true, message: 'BOM是否重新计价不能为空', trigger: 'blur' }],
  noExtraCharge: [{ required: true, message: '不进行加价设置不能为空', trigger: 'blur' }],
  costPriceByMaterial: [{ required: true, message: '按用料计算成本单价不能为空', trigger: 'blur' }],
  processQtyByProduct: [{ required: true, message: '工艺数量按成品推算不能为空', trigger: 'blur' }],
  noUploadFileByDefault: [{ required: true, message: '默认不上传文件不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseBoxTypeApi.getBaseBoxType(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BaseBoxTypeVO
    if (formType.value === 'create') {
      await BaseBoxTypeApi.createBaseBoxType(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseBoxTypeApi.updateBaseBoxType(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productTypeCode: undefined,
    productTypeName: undefined,
    productType: undefined,
    customerId: undefined,
    unitPriceInch: undefined,
    areaInch: undefined,
    volumeInch: undefined,
    weightInch: undefined,
    unitPriceCm: undefined,
    areaCm: undefined,
    volumeCm: undefined,
    weightCm: undefined,
    packageQuantity: undefined,
    specConcatMode: undefined,
    specSeparator: undefined,
    specUnit: undefined,
    defaultMaterialUnit: undefined,
    maxPaperLength: undefined,
    materialPriceUnit: undefined,
    deliveryPrice: undefined,
    deliveryTotalWeight: undefined,
    totalWeightRounding: undefined,
    roundingDigits: undefined,
    isDefault: undefined,
    defaultWithLoss: undefined,
    bomRecalculate: undefined,
    noExtraCharge: undefined,
    costPriceByMaterial: undefined,
    processQtyByProduct: undefined,
    noUploadFileByDefault: undefined
  }
  formRef.value?.resetFields()
}


// ** 客户 & 材质列表 ** 
const customerList = ref<{ id: string; name: string }[]>([])

/** 获取客户列表 */
const getAllBaseCustomer = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseCustomer();
    if (response) {
      customerList.value = response;
    }
  } catch (error) {
    console.error("获取客户列表失败:", error);
  }
}


/** 选择客户时，自动填充客户名称 */
const handleCustomerChange = (id: string) => {
  const selectedCustomer = customerList.value.find(item => item.id === id);
  formData.value.customerName = selectedCustomer ? selectedCustomer.name : "";
}

// 打开计算器
const calculatorRef = ref(null);
// 打开计算器
const openCalculator = (field, inputRef) => {
  calculatorRef.value.open((value) => {
    formData.value[field] = value;
  }, inputRef);
};

const calculatorRef1 = ref(null);
const openCalculator1 = (field, inputRef) => {
  calculatorRef1.value.open((value) => {
    formData.value[field] = value;
  }, inputRef);
};

onMounted(() => {
  Promise.all([
    getAllBaseCustomer()
  ])
})


</script>
